import type { Ref } from "vue";
import type { RoleDetailResult } from "@/api/types";
import { ref } from "vue";
import { roleApi } from "@/api";
import { apiCall } from "@/utils/http/apiCall";

interface UseRoleFormDialog {
    /** 对话框显隐 */
    dialogVisible: Ref<boolean>;
    /** 当前编辑数据 */
    editData: Ref<RoleDetailResult | null>;
    /** 打开新增 */
    openAddDialog: () => void;
    /** 打开编辑 */
    openEditDialog: (id: string) => void;
}

export function useRoleFormDialog(): UseRoleFormDialog {
    const dialogVisible = ref(false);
    const editData = ref<RoleDetailResult | null>(null);

    /** 打开新增 */
    function openAddDialog(): void {
        editData.value = null;
        dialogVisible.value = true;
    }

    /** 打开编辑 */
    function openEditDialog(id: string): void {
        apiCall(
            () => roleApi.findById(id),
            (data) => {
                editData.value = data;
                dialogVisible.value = true;
            },
        );
    }

    return {
        dialogVisible,
        editData,
        openAddDialog,
        openEditDialog,
    };
}
